/**
 * 
 */

package com.kugou.game.sdk.ui.fragment;

import com.kugou.framework.utils.NetWorkUtil;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseSDKWorkerFragment;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.interfaces.OnRequestListener;
import com.kugou.game.sdk.ui.dialog.BaseConfirmDialog;
import com.kugou.game.sdk.ui.widget.LoadingView;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.Rx;

import android.app.Activity;
import android.os.Bundle;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * 描述:找回支付密码
 *
 * @author jerryliu
 * @since 2015年8月20日 下午1:52:16
 */
public class SecurityPsdResetFragment extends BaseSDKWorkerFragment implements OnClickListener {
    private static final int MSG_UI_START_COUNT_DOWN = 11;

    private static final int MSG_BACK_REQUEST_VALIDATE_CODE = 12;

    private static final int MSG_UI_REQUEST_VALIDATE_CODE_SUCCESS = 13;

    private static final int MSG_UI_REQUEST_VALIDATE_CODE_FAILE = 14;

    private static final int MSG_BACK_RESET_PAY_PSD = 15;

    private static final int MSG_UI_RESET_PAY_PSD_SUCCESS = 16;

    private static final int MSG_UI_RESET_PAY_PSD_FAILE = 17;

    private Activity context;

    private TextView tvAccount, tvAccountHint, tvSecurityPhone, tvGetAuthCode, tvAuthCodeState,
            tvServicePhone, tvServiceQQ, tvNewPayPsdInputErrorTip, tvNewPayPsdInputErrorTip2;

    private EditText etAuthCode, etNewPayPsd, etNewPayPsdConfirm;

    private Button btnConfirm;

    private LoadingView loadingView;

    private View layoutContent, layoutService;

    private int countDownMinute = 60;

    private User user;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getActivity();
        user = UserManager.getInstance().getCurrentUserInternal();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(Rx.layout.kg_fragment_security_psd_reset, null);
        initView(view);
        setListener();
        return view;
    }

    private void initView(View view) {
        loadingView = (LoadingView) view.findViewById(Rx.id.kg_loadingView);
        loadingView.setText("正在操作，请稍候…");
        layoutContent = view.findViewById(Rx.id.kg_layout_bind_phone);
        tvAccount = (TextView) view.findViewById(Rx.id.kg_tv_username);
        tvAccount.setText(user.getAccountName());
        tvSecurityPhone = (TextView) view.findViewById(Rx.id.kg_binded_security_email);
        tvSecurityPhone.setText("安全手机：" + AppUtil.getPhoneWithStar(user.getBindPhoneNum()));
        tvAuthCodeState = (TextView) view.findViewById(Rx.id.kg_tv_auth_code_state);
        etAuthCode = (EditText) view.findViewById(Rx.id.kg_et_phone_number);
        tvGetAuthCode = (TextView) view.findViewById(Rx.id.kg_tv_get_auth_code);
        etNewPayPsd = (EditText) view.findViewById(Rx.id.kg_et_psd);
        etNewPayPsdConfirm = (EditText) view.findViewById(Rx.id.kg_et_auth_code);
        tvNewPayPsdInputErrorTip = (TextView) view.findViewById(Rx.id.kg_input_error_tip_1);
        tvNewPayPsdInputErrorTip2 = (TextView) view.findViewById(Rx.id.kg_input_error_tip_2);
        btnConfirm = (Button) view.findViewById(Rx.id.kg_btn_confirm);

        // 客服内容
        layoutService = view.findViewById(Rx.id.kg_ring_custom_service);
        tvAccountHint = (TextView) view.findViewById(Rx.id.kg_tv_account_hint);
        tvServicePhone = (TextView) view.findViewById(Rx.id.kg_tv_custom_server_phone);
        tvServicePhone.setText(Html.fromHtml("客服电话：<font color=\"#249EF6\">"
                + context.getString(Rx.string.kg_custom_service_phone) + "</font>"));
        tvServiceQQ = (TextView) view.findViewById(Rx.id.kg_tv_custom_server_qq);
        tvServiceQQ.setText(Html.fromHtml("客服QQ：<font color=\"#249EF6\">"
                + context.getString(Rx.string.kg_custom_service_qqnum) + "</font>"));
        if (TextUtils.isEmpty(user.getBindPhoneNum())) {
            layoutContent.setVisibility(View.GONE);
            tvAccountHint.setText(Html.fromHtml("酷狗账号：" + user.getAccountName() + "<br>"
                    + "<font>账号未绑定手机号码，请联系客服：</font>"));
        }
    }

    private void setListener() {
        tvGetAuthCode.setOnClickListener(this);
        btnConfirm.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        hideSoftInput(context);
        if (!NetWorkUtil.isNetworkAvailable(context)) {
            showToast("请检查您的网络连接");
            return;
        }
        if (v == tvGetAuthCode) {
            sendEmptyBackgroundMessage(MSG_BACK_REQUEST_VALIDATE_CODE);
        } else if (v == btnConfirm) {
            String code = etAuthCode.getText().toString().trim();
            if (TextUtils.isEmpty(code)) {
                showToast("请输入短信收到的验证码");
                return;
            }

            String newPayPsd = etNewPayPsd.getText().toString().trim();
            if (TextUtils.isEmpty(newPayPsd) || newPayPsd.length() != 6) {
                showToast("请输入6位新支付密码");
                tvNewPayPsdInputErrorTip.setText("请输入6位新支付密码");
                tvNewPayPsdInputErrorTip.setVisibility(View.VISIBLE);
                return;
            } else {
                tvNewPayPsdInputErrorTip.setVisibility(View.GONE);
            }

            String newPayPsdConfirm = etNewPayPsdConfirm.getText().toString().trim();
            if (TextUtils.isEmpty(newPayPsdConfirm)) {
                showToast("请再次输入新支付密码");
                tvNewPayPsdInputErrorTip2.setText("请再次输入新支付密码");
                tvNewPayPsdInputErrorTip2.setVisibility(View.VISIBLE);
                return;
            } else {
                tvNewPayPsdInputErrorTip2.setVisibility(View.GONE);
            }

            if (!newPayPsd.equals(newPayPsdConfirm)) {
                showToast("您两次输入的新支付密码不相同");
                tvNewPayPsdInputErrorTip2.setText("您两次输入的新支付密码不相同");
                tvNewPayPsdInputErrorTip2.setVisibility(View.VISIBLE);
                return;
            } else {
                tvNewPayPsdInputErrorTip2.setVisibility(View.GONE);
            }

            loadingView.setVisibility(View.VISIBLE);
            layoutContent.setVisibility(View.GONE);
            layoutService.setVisibility(View.GONE);

            sendEmptyBackgroundMessage(MSG_BACK_RESET_PAY_PSD);
        }
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        final Message message = new Message();
        String username = user.getAccountName();
        String kgToken = user.getKugouToken();
        String smscheckcode = etAuthCode.getText().toString().trim();
        String newPayPassword = etNewPayPsd.getText().toString().trim();
        String mobile = user.getBindPhoneNum();
        switch (msg.what) {
            case MSG_BACK_REQUEST_VALIDATE_CODE:
                sendEmptyUiMessage(MSG_UI_START_COUNT_DOWN);
                UserManager.getInstance().sendPayPsdCode(username, mobile, new OnRequestListener() {
                    @Override
                    public void onSuccess() {
                        message.what = MSG_UI_REQUEST_VALIDATE_CODE_SUCCESS;
                    }

                    @Override
                    public void onFailed(String errorMsg) {
                        message.what = MSG_UI_REQUEST_VALIDATE_CODE_FAILE;
                        message.obj = errorMsg;
                    }

                });
                break;
            case MSG_BACK_RESET_PAY_PSD:
                UserManager.getInstance().resetPayPsd(username, kgToken, smscheckcode,
                        newPayPassword, new OnRequestListener() {

                            @Override
                            public void onSuccess() {
                                message.what = MSG_UI_RESET_PAY_PSD_SUCCESS;
                            }

                            @Override
                            public void onFailed(String errorMsg) {
                                message.what = MSG_UI_RESET_PAY_PSD_FAILE;
                                message.obj = errorMsg;
                            }
                        });
                break;
        }
        sendUiMessage(message);
    }

    @Override
    public void handleUiMessage(Message msg) {
        if (getActivity() == null || getActivity().isFinishing() || isDetached() || !isAdded()) {
            return;
        }

        loadingView.setVisibility(View.GONE);
        layoutContent.setVisibility(View.VISIBLE);
        layoutService.setVisibility(View.VISIBLE);
        switch (msg.what) {
            case MSG_UI_START_COUNT_DOWN:
                if (countDownMinute > 0) {
                    tvGetAuthCode.setText(countDownMinute + "秒");
                    tvGetAuthCode.setEnabled(false);
                    countDownMinute--;
                    sendEmptyUiMessageDelayed(MSG_UI_START_COUNT_DOWN, 1000);
                } else {
                    tvGetAuthCode.setText("获取验证码");
                    tvGetAuthCode.setEnabled(true);
                    countDownMinute = 60;
                }
                break;
            case MSG_UI_REQUEST_VALIDATE_CODE_SUCCESS:
                showToast("验证码发送成功请注意查收");
                tvAuthCodeState.setVisibility(View.VISIBLE);
                tvAuthCodeState.setText(Html.fromHtml("已发送验证码到您的安全手机<font color=\"#249EF6\">"
                        + AppUtil.getPhoneWithStar(user.getBindPhoneNum()) + "</font>"));
                break;
            case MSG_UI_REQUEST_VALIDATE_CODE_FAILE:
                tvGetAuthCode.setText("获取验证码");
                tvGetAuthCode.setEnabled(true);
                countDownMinute = 60;
                if (msg.obj != null) {
                    showToast(msg.obj.toString());
                }
                break;
            case MSG_UI_RESET_PAY_PSD_SUCCESS:
                showSuccessDialog();
                break;
            case MSG_UI_RESET_PAY_PSD_FAILE:
                if (msg.obj != null) {
                    showToast(msg.obj.toString());
                }
                break;
        }
    }

    private void showSuccessDialog() {
        final BaseConfirmDialog dialog = new BaseConfirmDialog(context);
        dialog.setMessage("支付密码修改成功，请妥善保存以保证财产安全。");
        dialog.setSuccessLogoVisibility(View.VISIBLE);
        dialog.setDialogTitle("提示");
        dialog.setCancelBtnVisibility(View.GONE);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOKBtnText("知道了");
        dialog.setOkBtnBackground(Rx.drawable.kg_selector_bottom_single_filleted_corner_retangle);
        dialog.setCancelable(false);
        dialog.setOKClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
                if (getActivity() != null && !getActivity().isFinishing()) {
                    getActivity().finish();
                }
            }
        });
        dialog.show();
    }
}
